package com.qf.qfcenterservice.api;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.bean.R;
import com.qf.common.feigns.TenantApi;
import com.qf.common.model.QfTenant;
import com.qf.common.utils.JwtUtil;
import com.qf.common.utils.QfUtil;
import com.qf.qfcenterservice.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class TenantFeignApi implements TenantApi {

    @Autowired
    private TenantService tenantService;

    @PostMapping("/api/tenant/login")
    @Override
    public R login(@RequestBody QfTenant qfTenant) {

        String name = qfTenant.getName();
        //页面传递过来的明文密码
        String pwd = qfTenant.getPwd();

        if (StringUtils.isEmpty(name)){
            return R.fail(R.Code.FAILURE,"用户名不可以为空");
        }

        Wrapper<QfTenant> qw = Wrappers.lambdaQuery(QfTenant.class)
                .eq(QfTenant::getName,name);
        QfTenant tenant = tenantService.getOne(qw);

        if (tenant == null){
            return R.fail(R.Code.FAILURE,"用户名错误");
        }

        //数据库密码（md5加密）
        String sqlPwd = tenant.getPwd();

        if (!sqlPwd.equals(QfUtil.md5(pwd))){
            return R.fail(R.Code.FAILURE,"密码错误");
        }

        //返回jwt
        String id = UUID.randomUUID().toString().replaceAll("-","");
        String subject = tenant.getId(); //jwt中携带的是用户的id信息
        String jwt = JwtUtil.createJWT(id, subject, null);

        return R.ok(jwt);
    }
}
